# -*- coding:utf-8 -*-

from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from utils.common_util import CamelCaseUtil, export_list2excel
from module_admin.entity.vo.sys_table_vo import SysTablePageModel
from module_admin.service.sys_table_service import SysTableService
from utils.page_util import PageResponseModel
from module_stock.dao.daily_dao import DailyDao
from module_stock.entity.do.daily_do import Daily
from module_stock.entity.vo.daily_vo import DailyPageModel, DailyModel


class DailyService:
    """
    用户管理模块服务层
    """

    @classmethod
    async def get_daily_list(cls, query_db: AsyncSession, query_object: DailyPageModel, data_scope_sql: str) -> [list | PageResponseModel]:
        daily_list = await DailyDao.get_daily_list(query_db, query_object, data_scope_sql, is_page=True)
        return daily_list
    @classmethod
    async def get_daily_list_nopage(cls, query_db: AsyncSession, query_object: DailyPageModel, data_scope_sql: str = None) -> [list | PageResponseModel]:
        daily_list = await DailyDao.get_daily_list(query_db, query_object, data_scope_sql)
        return daily_list

    @classmethod
    async def get_daily_by_id(cls, query_db: AsyncSession, daily_id: int) -> DailyModel:
        daily = await  DailyDao.get_by_id(query_db, daily_id)
        daily_model = DailyModel(**CamelCaseUtil.transform_result(daily))
        return daily_model


    @classmethod
    async def add_daily(cls, query_db: AsyncSession, query_object: DailyModel) -> DailyModel:
        daily = await DailyDao.add_daily(query_db, query_object)
        daily_model = DailyModel(**CamelCaseUtil.transform_result(daily))
        return daily_model


    @classmethod
    async def update_daily(cls, query_db: AsyncSession, query_object: DailyModel) -> DailyModel:
        daily = await DailyDao.edit_daily(query_db, query_object)
        daily_model = DailyModel(**CamelCaseUtil.transform_result(daily))
        return daily_model


    @classmethod
    async def del_daily(cls, query_db: AsyncSession, daily_ids: List[str]):
        await DailyDao.del_daily(query_db, daily_ids)


    @classmethod
    async def export_daily_list(cls, query_db: AsyncSession, query_object: DailyPageModel, data_scope_sql) -> bytes:
        daily_list = await DailyDao.get_daily_list(query_db, query_object, data_scope_sql, is_page=False)
        filed_list = await SysTableService.get_sys_table_list(query_db, SysTablePageModel(tableName='daily'), is_page=False)
        filtered_filed = sorted(filter(lambda x: x["show"] == '1', filed_list), key=lambda x: x["sequence"])
        new_data = []
        for item in daily_list:
            mapping_dict = {}
            for fild in filtered_filed:
                if fild["prop"] in item:
                    mapping_dict[fild["label"]] = item[fild["prop"]]
            new_data.append(mapping_dict)
        binary_data = export_list2excel(new_data)
        return binary_data

    # 在 module_stock/service/daily_service.py 中添加以下方法（如果尚未存在）
    @staticmethod
    async def get_latest_trade_date(query_db: AsyncSession):
        """
        获取最新的交易日期
        """
        from module_stock.entity.do.daily_do import Daily
        from sqlalchemy import select, func

        latest_date_query = select(func.max(Daily.trade_date))
        latest_date_result = await query_db.execute(latest_date_query)
        latest_date = latest_date_result.scalar()

        return latest_date
